package com.sixth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.sixth.core.entity.*;
import com.sixth.core.vo.R;
import com.sixth.mapper.*;
import com.sixth.service.OrderChargeService;
import com.sixth.util.HttpClient;
import com.sixth.vo.OrderChargeItemVo;
import com.sixth.vo.OrderChargeVo;
import com.sixth.vo.OrderVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sixth.util.OrderUtil.getOrderNo;

@Service
public class OrderChargeServiceImpl extends ServiceImpl<OrderChargeMapper, OrderCharge> implements OrderChargeService {

    @Autowired
    private OrderChargeMapper orderChargeMapper;

    @Autowired
    private OrderChargeItemMapper orderChargeItemMapper;

    @Autowired
    private CareOrderItemMapper careOrderItemMapper;

    @Autowired
    private CareHistoryMapper careHistoryMapper;

    @Autowired
    private CareOrderMapper careOrderMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public R<IPage<OrderCharge>> selectByPage(OrderVo orderVo) {
        IPage<OrderCharge> page = new Page<>(orderVo.getPageNum(), orderVo.getPageSize());
        QueryWrapper<OrderCharge> wrapper = new QueryWrapper<>();

// 检查并添加查询条件
        if (orderVo.getRegId() != null && !orderVo.getRegId().trim().isEmpty()) {
            wrapper.eq("reg_id", orderVo.getRegId().trim());
        }
        if (orderVo.getPatientName() != null && !orderVo.getPatientName().trim().isEmpty()) {
            wrapper.eq("patient_name", orderVo.getPatientName().trim());
        }

// 按照 create_time 字段倒序排序
        wrapper.orderByDesc("create_time");

        IPage<OrderCharge> orderIPage = orderChargeMapper.selectPage(page, wrapper);
        return R.ok(orderIPage);
    }

    @Transactional
    @Override
    public R createNavigateCash(OrderChargeVo orderChargeVo) {
// 创建现金支付订单
        OrderCharge orderCharge = new OrderCharge();
        orderCharge.setOrderId(getOrderNo()); // 生成唯一订单号
        orderCharge.setChId(orderChargeVo.getChId());
        orderCharge.setOrderAmount(BigDecimal.valueOf(orderChargeVo.getOrderAmount()));
        orderCharge.setPatientName(orderChargeVo.getPatientName());
        orderCharge.setRegId(orderChargeVo.getRegId());
        orderCharge.setOrderStatus("1");
        orderCharge.setCreateTime(new Date());
        orderCharge.setPayPlatformId("");
        orderCharge.setPayTime(new Date());
        orderCharge.setPayType("0");
        orderCharge.setCreateBy(orderChargeVo.getCreateBy());
        orderChargeMapper.insert(orderCharge);

// 更新 CareOrderItem 状态
        List<String> itemIds = orderChargeVo.getOrderChargeItemDtoList().stream()
                .map(OrderChargeItemVo::getItemId)
                .collect(Collectors.toList());

        QueryWrapper<CareOrderItem> careOrderItemQuery = new QueryWrapper<>();
        careOrderItemQuery.in("item_id", itemIds);

        CareOrderItem careOrderItem = new CareOrderItem();
        careOrderItem.setStatus("1");
        careOrderItemMapper.update(careOrderItem, careOrderItemQuery);

// 写入支付订单详情表
        List<OrderChargeItem> orderChargeItemList = orderChargeVo.getOrderChargeItemDtoList().stream()
                .map(orderChargeItemVo -> {
                    OrderChargeItem orderChargeItem = new OrderChargeItem();
                    orderChargeItem.setCoId(orderChargeItemVo.getCoId());
                    orderChargeItem.setItemAmount(BigDecimal.valueOf(orderChargeItemVo.getItemAmount()));
                    orderChargeItem.setItemId(orderChargeItemVo.getItemId());
                    orderChargeItem.setItemName(orderChargeItemVo.getItemName());
                    orderChargeItem.setItemNum(BigDecimal.valueOf(orderChargeItemVo.getItemNum()));
                    orderChargeItem.setItemPrice(orderChargeItemVo.getItemPrice());
                    orderChargeItem.setItemType(orderChargeItemVo.getItemType());
                    orderChargeItem.setStatus("1");
                    orderChargeItem.setOrderId(orderCharge.getOrderId());
                    orderChargeItemMapper.insert(orderChargeItem);
                    return orderChargeItem;
                })
                .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("OrderId", orderCharge.getOrderId());
        result.put("OrderAmount", orderCharge.getOrderAmount());
        result.put("OrderChargeItemList", orderChargeItemList);

        return R.ok(result);
    }


    @Override
    public R createNavigateWenXin(OrderChargeVo orderChargeVo) {
// 创建微信付订单
        OrderCharge orderCharge = new OrderCharge();
        String orderId = getOrderNo(); // 生成唯一订单号
        orderCharge.setOrderId(orderId);
        orderCharge.setChId(orderChargeVo.getChId());
        orderCharge.setOrderAmount(BigDecimal.valueOf(orderChargeVo.getOrderAmount()));
        orderCharge.setPatientName(orderChargeVo.getPatientName());
        orderCharge.setRegId(orderChargeVo.getRegId());
        orderCharge.setOrderStatus("0");
        orderCharge.setCreateTime(new Date());
        orderCharge.setPayPlatformId("");
        orderCharge.setPayTime(new Date());
        orderCharge.setPayType("2");
        orderCharge.setCreateBy(orderChargeVo.getCreateBy());
        orderChargeMapper.insert(orderCharge);

// 写入支付订单详情表
        List<OrderChargeItem> orderChargeItemList = orderChargeVo.getOrderChargeItemDtoList().stream()
                .map(orderChargeItemVo -> {
                    OrderChargeItem orderChargeItem = new OrderChargeItem();
                    orderChargeItem.setCoId(orderChargeItemVo.getCoId());
                    orderChargeItem.setItemAmount(BigDecimal.valueOf(orderChargeItemVo.getItemAmount()));
                    orderChargeItem.setItemId(orderChargeItemVo.getItemId());
                    orderChargeItem.setItemName(orderChargeItemVo.getItemName());
                    orderChargeItem.setItemNum(BigDecimal.valueOf(orderChargeItemVo.getItemNum()));
                    orderChargeItem.setItemPrice(orderChargeItemVo.getItemPrice());
                    orderChargeItem.setItemType(orderChargeItemVo.getItemType());
                    orderChargeItem.setStatus("0");
                    orderChargeItem.setOrderId(orderCharge.getOrderId());
                    orderChargeItemMapper.insert(orderChargeItem);
                    return orderChargeItem;
                })
                .collect(Collectors.toList());

// 返回订单信息
        Map<String, String> responseData = new HashMap<>();
        responseData.put("orderId", orderId);
        // 发送消息到 RabbitMQ
        // 使用正确的 MessageProperties 类

        return R.ok(responseData);
    }

    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.mch_id}")
    private String mch_id;
    @Value("${weixin.api_key}")
    private String api_key;

    @Override
    public R queryPayStatus(String orderId) {
// 1.根据订单号查询出订单的信息
        QueryWrapper<OrderCharge> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("order_status", 0);
        OrderCharge order = orderChargeMapper.selectOne(queryWrapper);
        if (order != null) {
            // 设置请求的参数----格式为xml格式
            try {
                Map<String, String> params = new HashMap<>();
                params.put("appid", appid);
                params.put("mch_id", mch_id);
                params.put("nonce_str", WXPayUtil.generateNonceStr());
                params.put("body", order.getCreateBy());
                params.put("out_trade_no", orderId);
                params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
                params.put("spbill_create_ip", "127.0.0.1"); // 终端的IP
                params.put("notify_url", "http://localhost:8080/handlePayWithWx/back");
                params.put("trade_type", "NATIVE");

                // 创建并发送请求
                HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                client.setHttps(true);
                client.setXmlParam(WXPayUtil.generateSignedXml(params, api_key));
                client.post();
                String content = client.getContent();
                Map<String, String> resultMap = WXPayUtil.xmlToMap(content);

                if ("SUCCESS".equals(resultMap.get("return_code"))) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("code_url", resultMap.get("code_url"));
                    result.put("order_amount", order.getOrderAmount());
                    result.put("orderId", orderId);
                    MessageProperties messageProperties = new MessageProperties();
                    messageProperties.setHeader("orderId", orderId); // 使用 setHeader 来设置自定义头信息
                    Message message = new Message(orderId.getBytes(), messageProperties);
                    rabbitTemplate.convertAndSend("wx_order_exchange", "", message);
                    return R.ok(result);

                } else {
                    return R.error("订单创建失败");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return R.error("订单失效");
    }


    @Override
    public R queryPayStatus2(String orderId) {
        try {
            // 1.根据订单号查询订单信息
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            Map<String, String> params = new HashMap<>();
            params.put("appid", appid);
            params.put("mch_id", mch_id);
            params.put("out_trade_no", orderId);
            params.put("nonce_str", WXPayUtil.generateNonceStr());

            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params, api_key));
            client.post();
            String content = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);

            if ("SUCCESS".equals(map.get("trade_state"))) {
                // 更新订单状态
                OrderCharge order = new OrderCharge();
                order.setOrderStatus("1");
                order.setUpdateTime(new Date());
                QueryWrapper<OrderCharge> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_id", orderId);
                queryWrapper.eq("order_status", "0");
                orderChargeMapper.update(order, queryWrapper);

                // 更新支付记录表的记录
                OrderChargeItem orderChargeItem = new OrderChargeItem();
                orderChargeItem.setStatus("1");
                QueryWrapper<OrderChargeItem> queryWrapperItem = new QueryWrapper<>();
                queryWrapperItem.eq("order_id", orderId);
                queryWrapperItem.eq("status", "0");
                orderChargeItemMapper.update(orderChargeItem, queryWrapperItem);

                // 现在更新 CareOrderItem 的状态
                List<OrderChargeItem> orderChargeItems = orderChargeItemMapper.selectList(
                        new QueryWrapper<OrderChargeItem>().eq("order_id", orderId)
                );

                List<String> itemIds = orderChargeItems.stream()
                        .map(OrderChargeItem::getItemId)
                        .collect(Collectors.toList());

                if (!itemIds.isEmpty()) {
                    QueryWrapper<CareOrderItem> careOrderItemQuery = new QueryWrapper<>();
                    careOrderItemQuery.in("item_id", itemIds);

                    CareOrderItem careOrderItem = new CareOrderItem();
                    careOrderItem.setStatus("1");
                    careOrderItemMapper.update(careOrderItem, careOrderItemQuery);
                }

                return R.ok(200);
            } else {
                return R.error("支付未完成");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R appClient(List<String> itemIds) {


// 用循环方式，拿到orderChargeItemMapper里的金额
        BigDecimal totalAmount = BigDecimal.ZERO;

        for (String itemId : itemIds) {
            QueryWrapper<CareOrderItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("item_id", itemId);
            List<CareOrderItem> careOrderItemList = careOrderItemMapper.selectList(queryWrapper);

            totalAmount = totalAmount.add(
                    careOrderItemList.stream()
                            .map(CareOrderItem::getAmount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add)
            );
        }
// 拿到itemId，去orderChargeItemMapper查询coId
        QueryWrapper<CareOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("item_id", itemIds);
        List<CareOrderItem> careOrderItemList = careOrderItemMapper.selectList(queryWrapper);
        List<String> coIds = careOrderItemList.stream()
                .map(CareOrderItem::getCoId)
                .collect(Collectors.toList());
// 拿到coId，careOrderMapper查询chId,他们的chId一样要一个就行
        QueryWrapper<CareOrder> careOrderQuery = new QueryWrapper<>();
        careOrderQuery.in("co_id", coIds);
        List<CareOrder> careOrderList = careOrderMapper.selectList(careOrderQuery);
        String chId = careOrderList.get(0).getChId();
/*QueryWrapper<CareOrder> careOrderQuery = new QueryWrapper<>();
careOrderQuery.in("co_id", coIds);
List<CareOrder> careOrderList = careOrderMapper.selectList(careOrderQuery);
List<String> chIds = careOrderList.stream()
        .map(CareOrder::getChId)
        .collect(Collectors.toList());*/
//拿着chId，去orderChargeMapper查询一条数据
        QueryWrapper<CareHistory> orderChargeQuery = new QueryWrapper<>();
        orderChargeQuery.eq("ch_id", chId);
        CareHistory careHistory = careHistoryMapper.selectOne(orderChargeQuery);
// 1. 检查是否存在未支付的有效订单
        QueryWrapper<OrderCharge> queryWrapperChId = new QueryWrapper<>();
        queryWrapperChId.eq("ch_id", chId);
        queryWrapperChId.eq("order_status", "0");  // 假设订单状态 "0" 表示未支付
        OrderCharge existingOrder = orderChargeMapper.selectOne(queryWrapperChId);

        String orderId;
        if (existingOrder != null) {
            // 如果有未支付的有效订单，使用已有订单的orderId
            orderId = existingOrder.getOrderId();
        } else {

            // 创建app微信付订单
            OrderCharge orderCharge = new OrderCharge();
            orderId = getOrderNo();
            orderCharge.setOrderId(orderId);
            orderCharge.setChId(chId);
            orderCharge.setOrderAmount(totalAmount);
            orderCharge.setPatientName(careHistory.getPatientName());
            orderCharge.setRegId(careHistory.getRegId());
            orderCharge.setOrderStatus("0");
            orderCharge.setCreateTime(new Date());
            orderCharge.setPayPlatformId("");
            orderCharge.setPayTime(new Date());
            orderCharge.setPayType("2");
            orderCharge.setCreateBy(careHistory.getUserName());
            orderChargeMapper.insert(orderCharge);

            for (String itemId : itemIds) {
                OrderChargeItem orderChargeItem = new OrderChargeItem();
                QueryWrapper<CareOrderItem> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("item_id", itemId);
                CareOrderItem careOrderItem = careOrderItemMapper.selectOne(queryWrapper1);
                orderChargeItem.setItemId(itemId);
                orderChargeItem.setCoId(careOrderItem.getCoId());
                orderChargeItem.setItemName(careOrderItem.getItemName());
                orderChargeItem.setItemPrice(careOrderItem.getPrice());
                orderChargeItem.setItemNum(careOrderItem.getNum());
                orderChargeItem.setOrderId(orderId);
                orderChargeItem.setItemAmount(careOrderItem.getAmount());
                orderChargeItem.setItemType(careOrderItem.getItemType());
                orderChargeItem.setStatus("0");
                orderChargeItemMapper.insert(orderChargeItem);
            }
        }
// 2. 生成支付请求参数并发送请求
        try {
            Map<String, String> params = new HashMap<>();
            params.put("appid", appid);
            params.put("mch_id", mch_id);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("body", "支付订单" + orderId);
            params.put("out_trade_no", orderId);
            params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
            params.put("spbill_create_ip", "127.0.0.1"); // 终端的IP
            params.put("notify_url", "http://localhost:8080/handlePayWithWx/back");
            params.put("trade_type", "NATIVE");

            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params, api_key));
            client.post();
            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);

            if ("SUCCESS".equals(resultMap.get("return_code"))) {
                // 返回支付二维码链接
                Map<String, Object> result = new HashMap<>();
                result.put("codeUrl", resultMap.get("code_url"));
                result.put("price", totalAmount);
                result.put("orderNo", orderId);

                // 使用正确的 MessageProperties 类
                MessageProperties messageProperties = new MessageProperties();
                messageProperties.setHeader("orderId", orderId); // 使用 setHeader 来设置自定义头信息
                Message message = new Message(orderId.getBytes(), messageProperties);

                // 发送消息到 RabbitMQ
                rabbitTemplate.convertAndSend("wx_order_exchange", "", message);
                return R.ok(result);
            } else {
                return R.error("订单创建失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
